package com.xhsj.user.hr.process.hrLeaveProcess.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhsj.user.hr.process.dto.hrLeaveProcess.*;
import com.xhsj.user.hr.process.dto.processDefinition.HandleAuditDto;
import com.xhsj.user.hr.process.hrEntryProcess.mapper.TbHrApprovalEntryApplyMapper;
import com.xhsj.user.hr.process.hrLeaveProcess.entity.TbHrApprovalLeaveTime;
import com.xhsj.user.hr.process.hrLeaveProcess.mapper.TbHrApprovalLeaveTimeMapper;
import com.xhsj.user.hr.process.hrLeaveProcess.query.*;
import com.xhsj.user.hr.process.hrLeaveProcess.vo.FindToDoListVo;
import com.xhsj.user.hr.process.message.service.TbProjectMessageService;
import com.xhsj.user.hr.process.processDefinition.query.MapQuery;
import com.xhsj.user.hr.process.query.ApprovalQuery;
import com.xhsj.user.hr.system.entity.TbHrLeaveUseNum;
import com.xhsj.user.hr.system.entity.TbHrUserSocialSecurity;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.mapper.TbHrLeaveHiUseNumMapper;
import com.xhsj.user.hr.system.mapper.TbHrLeaveUseNumMapper;
import com.xhsj.user.hr.system.mapper.TbHrUserSocialSecurityMapper;
import com.xhsj.user.hr.system.service.TbHrLeaveUsableLengthService;
import com.xhsj.user.utils.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;


import com.xhsj.user.hr.process.hrLeaveProcess.service.TbHrApprovalLeaveApplyService;
import com.xhsj.user.hr.process.hrLeaveProcess.entity.TbHrApprovalLeaveApply;

import javax.validation.Valid;


/**
 * <p>
 * 流程-hr请假申请表 前端控制器
 * </p>
 *
 * @author liuqinghua
 * @since Sep 1, 2020 10:07:11 AM
 */
@Slf4j
@Api(tags = "流程-hr请假申请表")
@RestController
@RequestMapping("/hrLeaveProcess/tbHrApprovalLeaveApply")
public class TbHrApprovalLeaveApplyController {

	@Autowired
	public TbHrApprovalLeaveApplyService service;

	// 项目消息 服务实现类
	@Autowired
	public TbProjectMessageService tbProjectMessageService;

	@Autowired
	private TbHrLeaveUsableLengthService tbHrLeaveUsableLengthService;

	@Autowired
	private TbHrLeaveUseNumMapper tbHrLeaveUseNumMapper;
	@Autowired
	private TbGlobalUserMapper tbGlobalUserMapper;
    @Autowired
    private TbHrApprovalLeaveTimeMapper tbHrApprovalLeaveTimeMapper;
    @Autowired
    private TbHrUserSocialSecurityMapper tbHrUserSocialSecurityMapper;
    @Autowired
    private TbHrLeaveHiUseNumMapper tbHrLeaveHiUseNumMapper;

	/**
	 * 保存/修改
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "流程-hr请假申请表,保存/修改", notes = "流程-hr请假申请表,保存和修改方法")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	// @PreAuthorize("hasAuthority('tb:hr:approval:leave:apply:edit')")
	public Message save(@RequestBody TbHrApprovalLeaveApply data){
		try {
			service.save(data);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("保存失败:{}",e);
			return Message.error(1,"失败");
		}

	}

	/**
	 * 通过id删除数据
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "流程-hr请假申请表删除", notes = "通过id删除流程-hr请假申请表信息。")
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	// @PreAuthorize("hasAuthority('tb:hr:approval:leave:apply:delete')")
	public Message delete(@RequestParam(value="id") String id) {
		try {
			service.removeById(id);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("删除失败:{}",e);
			return Message.error(1,"失败");
		}

	}

	/**
	 * 批量删除
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "批量删除", notes = "批量删除。")
	@RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
	public Message batchDelete(@RequestBody List<String> list) {
		try {
			service.removeByIds(list);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("删除失败:{}",e);
			return Message.error(1,"失败");
		}
	}

	/**
	 * 分页查询数据
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "分页查询流程-hr请假申请表list", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
	@RequestMapping(value="/findList",method = RequestMethod.POST)
	// @PreAuthorize("hasAuthority('tb:hr:approval:leave:apply:view')")
	public Message findList(@RequestBody Map<String,Object> data) {
		try {
			IPage<TbHrApprovalLeaveApply> selectPage = service.selectPage(data);
			return Message.success("成功",selectPage.getRecords(),selectPage.getTotal(),selectPage.getPages());
		} catch (Exception e) {
			log.error("查询异常:{}",e);
			return Message.error(1,"失败");
		}
	}

	/**
	 * 查询所有数据
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "查询流程-hr请假申请表所有数据list", notes = "查询流程-hr请假申请表所有数据list。")
	@RequestMapping(value="/findAll",method = RequestMethod.POST)
	// @PreAuthorize("hasAuthority('tb:hr:approval:leave:apply:view')")
	public Message findAll(){
		return Message.success("成功",service.selectAll());
	}

	/**
	 * 通过id获取实体类
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "通过id获取流程-hr请假申请表实体类", notes = "通过id获取流程-hr请假申请表实体类。")
	@RequestMapping(value="/getById",method = RequestMethod.GET)
	// @PreAuthorize("hasAuthority('tb:hr:approval:leave:apply:view')")
	public Message getById(@RequestParam(value="id") String id) {
		return Message.success("成功",service.getById(id));
	}

	/**
	 * 通过id查询详细信息
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "通过id获取实体类详细信息", notes = "通过id获取实体类详细信息。")
	@RequestMapping(value="/detail",method = RequestMethod.GET)
	// @PreAuthorize("hasAuthority('tb:hr:approval:leave:apply:view')")
	public Message detail(@RequestParam(value="id") String id) {
		return Message.success("成功",service.getById(id));
	}


	/**
	 * 请假流程启动
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "请假流程启动", notes = "请假流程启动。")
	@PostMapping(value="/startLeaveApply")
	public Message startLeaveApply(@RequestBody HrLeaveApplyStartDto data) throws Exception {
		try {
			ApprovalQuery approvalQuery = service.startLeaveApply(data);
			//保存消息
			CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
				tbProjectMessageService.sendMessageCommon(approvalQuery);
			});
			return Message.success("成功");
		} catch (Exception e) {
			log.error("查询异常:{}",e);
			return Message.error(1,e.getMessage());
		}
	}

	/***
	 * 销假
	 * @author 苏小林
	 * @date 2021/6/1 11:03
	 * @param: data
	 * @return: com.xhsj.user.utils.Message
	 */
	@ApiOperation(value = "销假", notes = "销假。")
//	@PreAuthorize("hasAuthority('tb:hr:approval:cancellation:apply:edit')")
	@PostMapping(value="/cancellationApply")
	public Message cancellationApply(@RequestBody HrLeaveApplyStartDto data) {
		try {
			ApprovalQuery approvalQuery = service.cancellationApply(data);
			//保存消息
			CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
				tbProjectMessageService.sendMessageCommon(approvalQuery);
			});
			return Message.success("成功");
		} catch (Exception e) {
			log.error("查询异常:{}",e);
			return Message.error(1,e.getMessage());
		}
	}


	/**
	 * 申请人请假流程重新提交
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "申请人请假流程重新提交", notes = "申请人请假流程重新提交")
	@PostMapping(value="/returnLeaveApply")
	public Message returnLeaveApply(@RequestBody ReturnLeaveApplyDto data){
		try {
			ApprovalQuery approvalQuery = service.returnLeaveApply(data);
			//保存消息
			CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
				tbProjectMessageService.sendMessageCommon(approvalQuery);
			});
			return Message.success("成功");
		} catch (Exception e) {
			log.error("查询异常:{}",e);
			return Message.error(1,e.getMessage());
		}

	}

	/**
	 * 请假流程审批
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "请假流程审批", notes = "请假流程审批。")
	@PostMapping(value="/approvalLeaveApply")
	public Message approvalLeaveApplyProcess(@RequestBody @Valid HandleAuditDto data, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			log.info(bindingResult.getFieldError().getDefaultMessage());
			return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			ApprovalQuery approvalQuery = service.approvalLeaveApply(data);
			//保存消息
			CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
				tbProjectMessageService.sendMessageCommon(approvalQuery);
			});
			return Message.success("成功");
		} catch (Exception e) {
			log.error("异常:{}",e);
			return Message.error(1,e.getMessage());
		}

	}

	/**
	 * 请假流程作废
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "请假流程作废", notes = "请假流程作废")
	@PostMapping(value="/approvalLeaveToVoidApply")
	public Message approvalLeaveToVoidApply(@RequestBody @Valid ApprovalLeaveToVoidApplyDto data, BindingResult bindingResult) throws Exception {
		if (bindingResult.hasErrors()) {
			log.info(bindingResult.getFieldError().getDefaultMessage());
			return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
		}
		ApprovalQuery approvalQuery = service.approvalLeaveToVoidApply(data);
		return Message.success("成功");
	}

	/**
	 * 我的请假申请
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "我的请假申请列表", notes = "我的请假申请列表")
	@PostMapping(value="/myLeaveApplyList")
	@PreAuthorize("hasAuthority('tb:hr:approval:leave:apply:my:view')")
	public Message myLeaveApplyList(@RequestBody @Valid MyLeaveApplyListDto data, BindingResult bindingResult) throws Exception {
		log.info("我的请假申请列表参数{}", data);
		if (bindingResult.hasErrors()) {
			log.info(bindingResult.getFieldError().getDefaultMessage());
			return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
		}
		Page<MyLeaveApplyListQuery> myLeaveApplyListQueryPage = service.myLeaveApplyList(data);
		List<MyLeaveApplyListQuery> records = myLeaveApplyListQueryPage.getRecords();
		return Message.success("成功",records,myLeaveApplyListQueryPage.getTotal(),myLeaveApplyListQueryPage.getPages());
	}


	/**
	 * 获取请假原数据
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "获取请假原数据", notes = "获取请假原数据")
	@GetMapping(value="/myOriginalLeaveApplyList")
	public Message myOriginalLeaveApplyList(@RequestParam("oldId") Long oldId) throws Exception {

		List<AllLeaveTimeListByLeaveDateQuery> myLeaveApplyListQueryPage = service.myOriginalLeaveApplyList(oldId);
		return Message.success("成功",myLeaveApplyListQueryPage);
	}

	/**
	 * 全部请假申请列表
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "全部请假申请列表", notes = "全部请假申请列表")
	@PostMapping(value="/allLeaveApplyList")
	@PreAuthorize("hasAuthority('tb:hr:approval:leave:apply:all:view')")
	public Message allLeaveApplyList(@RequestBody @Valid MyLeaveApplyListDto data, BindingResult bindingResult) throws Exception {
		log.info("全部请假申请列表参数{}", data);
		if (bindingResult.hasErrors()) {
			log.info(bindingResult.getFieldError().getDefaultMessage());
			return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
		}

		// 按日期查询
		if (data.getLeaveDate() != null) {
			IPage<AllLeaveApplyListByLeaveDateQuery> allLeaveApplyListByLeaveDateQueryIPage = service.allLeaveApplyListByLeaveDate(data);
			List<AllLeaveApplyListByLeaveDateQuery> records = allLeaveApplyListByLeaveDateQueryIPage.getRecords();
			records = this.detailLeaveApplyListByLeaveDate(records,data.getLeaveDate());
			return Message.success("成功",records,allLeaveApplyListByLeaveDateQueryIPage.getTotal(),allLeaveApplyListByLeaveDateQueryIPage.getPages());
		}else{
			Page<MyLeaveApplyListQuery> myLeaveApplyListQueryPage = service.allLeaveApplyList(data);
			List<MyLeaveApplyListQuery> records = myLeaveApplyListQueryPage.getRecords();
			records = this.detailLeaveApplyList(records);
			return Message.success("成功",records,myLeaveApplyListQueryPage.getTotal(),myLeaveApplyListQueryPage.getPages());
		}

	}

	// 时间处理
	public BigDecimal  detailUtil( BigDecimal dayCoincidence,String startTime,String stopTime,Date startDate,Date stopDate,
								   Date firstDate,Date lastDate) throws ParseException {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		startTime = startTime+":00";
		stopTime = stopTime+":00";
		String startFormatterDate1 = formatter.format(startDate);
		String stopFormatterDate1 = formatter.format(stopDate);
		startDate = dateFormat.parse(startFormatterDate1 +" "+ startTime);
		stopDate = dateFormat.parse(stopFormatterDate1 +" "+ stopTime);
		System.out.println(MyDateUtil.getDayCoincidence(startDate, stopDate, firstDate, lastDate));
//		if ("0".equals(String.valueOf(operationType))) {
		dayCoincidence = dayCoincidence.add(MyDateUtil.getDayCoincidence(startDate, stopDate, firstDate, lastDate));
//		}else if ("2".equals(String.valueOf(operationType))) {
//			dayCoincidence= dayCoincidence.subtract(MyDateUtil.getDayCoincidence(startDate, stopDate, firstDate, lastDate)).abs();
//		}

		return dayCoincidence;
	}

	// 处理请假时间
	public List<AllLeaveApplyListByLeaveDateQuery> detailLeaveApplyListByLeaveDate(List<AllLeaveApplyListByLeaveDateQuery> records,
																				   Date leaveDate) throws ParseException {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		// 获取月份的第一天和最后一天
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(leaveDate);
		String[] thisMonth = MyDateUtil.getThisMonth(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)).split(",");
		// 第一天
		Date firstDate = dateFormat.parse(thisMonth[0]+" 09:00:00");
		// 最后一天
		Date lastDate = dateFormat.parse(thisMonth[1]+" 18:00:00");
		for (AllLeaveApplyListByLeaveDateQuery record : records) {
			List<AllLeaveTimeListByLeaveDateQuery> allLeaveTimeListByLeaveDateQueryList = record.getAllLeaveTimeListByLeaveDateQueryList();
			BigDecimal dayCoincidence = new BigDecimal(0);
			for (AllLeaveTimeListByLeaveDateQuery leaveTime:allLeaveTimeListByLeaveDateQueryList) {
				dayCoincidence = this.detailUtil(dayCoincidence,leaveTime.getStartTime(),leaveTime.getStopTime(),leaveTime.getStartDate(),
						leaveTime.getStopDate(),firstDate,lastDate);

			}

			// 保存时间
			String resultLeaveTimes = this.detailLeaveTimesUtil(dayCoincidence);
			record.setLeaveTimes(resultLeaveTimes);
		}
		return records;
	}

	public String detailLeaveTimesUtil(BigDecimal leaveTimes){
		String resultLeaveTimes = "";
		if (leaveTimes == null) {
			leaveTimes = new BigDecimal(0);
		}
		log.debug("leaveTimesleaveTimesleaveTimes"+leaveTimes);
		BigDecimal[] bigDecimals = leaveTimes.divideAndRemainder(new BigDecimal(8));
		BigDecimal first= bigDecimals[0];
		BigDecimal last= bigDecimals[1];
		if (first.compareTo(BigDecimal.ZERO) != 0) {
			resultLeaveTimes = first + "天";
		}
		if (last.compareTo(BigDecimal.ZERO) != 0) {
			resultLeaveTimes = resultLeaveTimes+last+"小时";
		}
		return resultLeaveTimes;
	}

	// 处理请假时间
	public List<MyLeaveApplyListQuery> detailLeaveApplyList(List<MyLeaveApplyListQuery> records){
		for (MyLeaveApplyListQuery record : records) {
			// 保存时间
			String resultLeaveTimes = this.detailLeaveTimesUtil(record.getDays());
			record.setLeaveTimes(resultLeaveTimes);
		}
		return records;
	}


	/**
	 * 待审核请假申请列表
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "待审核请假申请列表", notes = "待审核请假申请列表")
	@PostMapping(value="/runLeaveApplyList")
	public Message runLeaveApplyList(@RequestBody @Valid RunLeaveApplyListDto data, BindingResult bindingResult) throws Exception {
		log.info("待审核请假申请列表参数{}", data);
		if (bindingResult.hasErrors()) {
			log.info(bindingResult.getFieldError().getDefaultMessage());
			return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
		}
		Page<RunLeaveApplyListQuery> myLeaveApplyListQueryPage = service.runLeaveApplyList(data);
		return Message.success("成功",myLeaveApplyListQueryPage.getRecords(),myLeaveApplyListQueryPage.getTotal(),myLeaveApplyListQueryPage.getPages());
	}

	/**
	 * 已审核请假申请列表
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "已审核请假申请列表", notes = "已审核请假申请列表")
	@PostMapping(value="/completedLeaveApplyList")
	public Message completedLeaveApplyList(@RequestBody @Valid RunLeaveApplyListDto data, BindingResult bindingResult) throws Exception {
		log.info("已审核请假申请列表参数{}", data);
		if (bindingResult.hasErrors()) {
			log.info(bindingResult.getFieldError().getDefaultMessage());
			return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
		}
		Page<CompletedLeaveApplyList> completedLeaveApplyList = service.completedLeaveApplyList(data);
		return Message.success("成功",completedLeaveApplyList.getRecords(),completedLeaveApplyList.getTotal(),completedLeaveApplyList.getPages());
	}

	/**
	 * 我的请假申请详细信息
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "我的请假申请详细信息", notes = "我的请假申请详细信息")
	@GetMapping(value="/myLeaveApplyDetailedList")
	public Message myLeaveApplyDetailedList(@RequestParam("dataId") Long dataId,
											@RequestParam("businessId") Long businessId,
											@RequestParam(value = "operationType",required = false) Integer operationType) throws Exception {
		log.info("我的请假申请详细信息参数{},{},{}", dataId,businessId);
		MyLeaveApplyDetailedListQuery myLeaveApplyListQuery = service.myLeaveApplyDetailedList(dataId,businessId,operationType);
		return Message.success("成功",myLeaveApplyListQuery);
	}

	/**
	 * 我的请假申请删除
	 * @author liuqinghua
	 * @date Sep 1, 2020 10:07:11 AM
	 */
	@ApiOperation(value = "我的请假申请删除", notes = "我的请假申请删除")
	@GetMapping(value="/deleteMyLeaveApply")
	public Message deleteMyLeaveApply(@RequestParam("dataId") Long dataId) throws Exception {
		try {
			log.info("我的请假申请删除参数{}", dataId);
			service.deleteMyLeaveApply(dataId);
		} catch (Exception e) {
			log.error("失败",e);
			return Message.error(e.getMessage());
		}
		return Message.success("成功");
	}

	@ApiOperation(value = "获取已调休时间,加班时间，剩余调休时间", notes = "获取已调休时间,加班时间，剩余调休时间")
	@RequestMapping(value="/getCompensatoryLeaveTime",method = RequestMethod.GET)
	public Message getCompensatoryLeaveTime(@RequestParam(value = "userId",required = false) Long userId) {
		try {

			if (StringUtils.isBlank(userId)) {
				userId = UserUtils.getLoginAppUser().getUserId();
			}
			CompensatoryLeaveTimeQuery overTimeUsableLength = tbHrLeaveUsableLengthService.getOverTimeUsableLength(userId,LocalDate.now());
			return Message.success("成功",overTimeUsableLength);
		} catch (ParseException e) {
			log.error("失败",e);
			return Message.error("失败");
		}

	}



	/**
	 * 查询待办列表
	 * @author 苏小林
	 * @date 2021/4/14 15:50
	 * @param: baseParam
	 * @return: com.xhsj.user.utils.Message
	 */
	@PostMapping("/findToList")
	public Message findToList(@RequestBody FindToDoListQuery baseParam) {

		try {
			IPage<FindToDoListVo> toList = service.findToList(baseParam);
			return Message.success("成功",toList.getRecords(),toList.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error();
		}
	}


	/**
	 * @Description: 请假统计图数据
	 * @Param:date 日期
	 * @Author: liuqinghua
	 * @Date: 2021/9/6
	 */
	@ApiOperation(value = "请假统计图数据", notes = "请假统计图数据")
	@RequestMapping(value="/getLeaveStatistics",method = RequestMethod.GET)
	public Message getLeaveStatistics(@RequestParam(value = "date") String date) {
		try {
			// 判断日期格式是否正确
			if(!Pattern.matches( DateUtils.MONTH_REGEX, date))
				return Message.error("日期格式不对，请按照yyyy-MM");
			List<Map<String,Integer>> data = service.getLeaveStatistics(date);
			return Message.success("成功",data);
		} catch (Exception e) {
			log.error("失败",e);
			return Message.error("失败");
		}

	}

	@ApiOperation(value = "年假日期修改", notes = "年假日期修改")
	@RequestMapping(value="/updateAnnualLeave",method = RequestMethod.POST)
	public Message updateAnnualLeave(@RequestBody TbHrUserSocialSecurity tbHrUserSocialSecurity) {
		try {
		 // 年假日期修改
		 service.updateAnnualLeave(tbHrUserSocialSecurity);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("失败",e);
			return Message.error(e.getMessage());
		}

	}

	public static void main(String[] args) {
		Month month = LocalDate.now().getMonth();
		System.out.println( LocalDate.now().minusYears(1));
		LocalDate ocalDate = LocalDate.now().minusYears(1);
		Date yearEnd = Date.from(ocalDate.plusYears(1).with(TemporalAdjusters.lastDayOfYear()).atStartOfDay(ZoneId.systemDefault()).toInstant());
		System.out.println( ocalDate.plusYears(1).with(TemporalAdjusters.firstDayOfYear()));

		System.out.println(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()));
		System.out.println(0 > 0 ? 1 : 0);

	}

	// 迁徙数据
	@Transactional(rollbackFor = Exception.class)
	@RequestMapping(value="/data",method = RequestMethod.GET)
	public Message data() throws Exception {
		tbHrLeaveUseNumMapper.deleteAll();
        tbHrLeaveHiUseNumMapper.deleteAll();
		try {
			List<MapQuery> allUsers = tbGlobalUserMapper.getAllUsers();
			for (MapQuery allUser : allUsers) {
				long userId =allUser.getValue();
                TbHrUserSocialSecurity entity = tbHrUserSocialSecurityMapper.getUserSocialSecurity(userId);
                TbHrLeaveUseNum tbHrLeaveUseNum = service.data(userId, null, 0);
				// 获取未完结的申请
                List<TbHrApprovalLeaveApply> list = service.getList(userId, 3);
                for(TbHrApprovalLeaveApply id:list) {

                        // 删除
                        tbHrLeaveUseNumMapper.deleteByData(tbHrLeaveUseNum.getYear(), tbHrLeaveUseNum.getSocialSecurityId());
                        tbHrLeaveUseNum.setUseNum(entity.getUseNum());
                        if (tbHrLeaveUseNumMapper.insert(tbHrLeaveUseNum) != 1) {
                            throw new Exception("保存年假已休表异常");
                        }
                        tbHrLeaveHiUseNumMapper.deleteByDataId(id.getId());

                        QueryWrapper<TbHrApprovalLeaveTime> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("data_id", id.getId());
                        List<TbHrApprovalLeaveTime> tbHrApprovalLeaveTimes = tbHrApprovalLeaveTimeMapper.selectList(queryWrapper);
                        service.upDateTime(tbHrApprovalLeaveTimes, entity);

                }

			}
			return Message.success("成功");
		} catch (Exception e) {
			log.error("失败",e);
			return Message.error("失败");
		}
	}


}

